package com.aaa.gs.filter;

import com.aaa.common.util.Result;
import com.aaa.common.util.ResultStatus;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;

/**
 * @ fileName:IllegalIPFilter
 * @ description:
 * @ author:诸葛龙辰
 * @ createTime:2023/6/12 14:16
 * @ version:1.0.0
 */
@Component
public class IllegalIPFilter implements GlobalFilter, Ordered {

    @Value("${illegal-IP}")
    private String illegalIP;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("您进入了非法IP过滤器。。。。。。。。。。。。。。。。。。");
        //获取request 和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取IP
        InetAddress inetAddress = request.getRemoteAddress().getAddress();
        String hostName = inetAddress.getHostName();
        System.out.println("访问的主机名称为："+hostName);
        String hostAddress = inetAddress.getHostAddress();
        System.out.println("访问的IP为："+hostAddress);

        //"172.16.9.62,172.16.9.67,172.16.9.68,172.16.9.61".contains("172.16.9.67")   =true
        if(illegalIP.contains(hostAddress)){
            //定义返回map对象
            Result result =new Result(ResultStatus.ILLEGAL_IP_ERROR.getReturnCode(),
                    ResultStatus.ILLEGAL_IP_ERROR.getReturnMsg(),"非法IP！");
            byte[] bytesMap = null;
            try {
                //把map转换为字节数组
                bytesMap = JSON.toJSONString(result).getBytes("GBK");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //spring 提供数据缓冲类  使用response.bufferFactory()中提供的wrap方法，把字节数组转换为DataBuffer
            DataBuffer dataBuffer = response.bufferFactory().wrap(bytesMap);
            //writeWith 向响应对象中写入影响数据  需要的是Publisher接口的实现类   Mono就是该接口的实现类
            return response.writeWith(Mono.just(dataBuffer));
        }
        //让程序继续运行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 5;
    }
}
